const { ccclass, property } = cc._decorator;


import l from "./AudioManager"
import s from "./PeripheralSystemDataMgr"
import c from "./EventMgr"
import u from "./GameEventType"
import p from "./frameworkManager"
import d from "./EngineUtil"
var h = ["reward_1", "reward_fund", "reward_2", "reward_3", "reward_4"]

var n = cc.Enum({
    redPaper: 0,
    fund: 1,
    prop: 2
});

@ccclass
export default class EffectsCtrl extends cc.Component {
    effectPool = new cc.NodePool();
    tarNodes = [];
    load_imgs = [];
    effectPrefab = null;
    isEnableWork = false;

    onLoad() {
        c.listen(u.SHOWEFFECT_FLYINGRED, this.addEffects, this);
        c.listen(u.SET_EFFECT_TARGETS, this.setTargetNodes, this);
    }

    onDestroy() {
        c.ignore(u.SHOWEFFECT_FLYINGRED, this.addEffects, this);
        c.ignore(u.SET_EFFECT_TARGETS, this.setTargetNodes, this);
    }

    start() {
        this.loadSpriteFrames();
        this.loadPrefabs();
    }

    loadSpriteFrames() {
        const h = ["reward_1", "reward_fund", "reward_2", "reward_3", "reward_4"];
        for (let i = 0; i < h.length; i++) {
            const a = "imgs/clickEveryDay/" + h[i];
            cc.loader.loadRes(a, cc.SpriteFrame, (err, spriteFrame) => {
                if (err) {
                    cc.error(err.message || err);
                } else if (spriteFrame instanceof cc.SpriteFrame) {
                    this.load_imgs[i] = spriteFrame;
                    p.log("加载图片=======", this.load_imgs);
                }
            });
        }
    }

    loadPrefabs() {
        cc.loader.loadRes("prefabs/TravelToolEffect", cc.Prefab, (err, prefab) => {
            if (err) {
                cc.error(err.message || err);
            } else if (prefab instanceof cc.Prefab) {
                this.effectPrefab = prefab;
                p.log("加载预制体=======", this.effectPrefab);
            }
        });
    }

    addEffects(data) {
        if (!this.isEnableWork) {
            this.tarNodes = s.getTopTagArr();
            p.log("目标节点获取失败=======", this.tarNodes);
        }

        const { startPos, endPos, type, callback, reward } = data;

        let targetPos = endPos;
        if (!targetPos) {
            let targetNode = this.getTagNodeByType(type);
            if (type >= n.prop) {
                targetNode = this.getTagNodeByType(this.tarNodes.length - 1);
            }
            const convertedPos = d.convertNodePosition(this.node, targetNode);
            targetPos = cc.v2(convertedPos.x, convertedPos.y);
        }

        this.addEffect(startPos, targetPos, type, callback, reward);
    }

    addEffect(startPos, targetPos, type, callback, reward) {
        if (startPos && targetPos) {
            const effectPrefab = this.effectPrefab;
            if (effectPrefab) {
                let count = 1;
                if (type >= n.prop) {
                    if (reward && reward > 0) {
                        count = 1;
                    }
                } else {
                    count = 5;
                }

                const effects = [];
                for (let i = 0; i < count; i++) {
                    const effectNode = this.effectPool.size() > 0 ? this.effectPool.get() : cc.instantiate(effectPrefab);
                    if (count === 5) {
                        effectNode.y = startPos.y + 10 * i;
                        effectNode.x = startPos.x;
                    } else {
                        effectNode.setPosition(startPos);
                    }
                    effects.push(effectNode);
                }

                this.playFlyAction(effects, reward, type, targetPos, callback);
            } else {
                p.error("effect error");
            }
        } else {
            p.error("effect 起始坐标为null请检查");
        }
    }

    playFlyAction(effects, reward, type, targetPos, callback) {
        const isClockDayAction = this.isClockDayAction(type, reward);
        effects = effects.reverse();

        for (let i = 0; i < effects.length; i++) {
            const effectNode = effects[i];
            effectNode.active = true;

            const countNode = effectNode.getChildByName("countNode");
            if (countNode) {
                countNode.active = false;
            }

            const rewardNode = effectNode.getChildByName("reward");
            rewardNode.getComponent(cc.Sprite).spriteFrame = this.load_imgs[type];
            rewardNode.scale = type >= n.prop ? 1.5 : 1.2;

            const scaleValue = type >= n.prop ? 0 : 1.2;
            const opacityValue = type >= n.prop ? 0 : 255;

            effectNode.scale = scaleValue;
            effectNode.opacity = opacityValue;

            const spineNode = effectNode.getChildByName("spineNode");
            spineNode.active = false;

            let duration = 0.1 * i;
            let moveScale = 1.2;

            if (isClockDayAction) {
                this.setCountNodeShow(effectNode, type, reward);
                spineNode.active = true;
                duration = 0.5;
                moveScale = 0.7;

                const spine = spineNode.getComponent(sp.Skeleton);
                this.scheduleOnce(() => {
                    d.playSpine(spine, "idle_1", false);
                });
            }

            cc.tween(effectNode)
                .to(duration, { scale: 1, opacity: 255 })
                .call(() => {
                    if (isClockDayAction) {
                        spineNode.active = false;
                        this.playEffectMusic(type);
                    } else if (i === effects.length - 1) {
                        this.playEffectMusic(type);
                    }
                })
                .to(moveScale, { x: targetPos.x, y: targetPos.y }, { easing: "backIn" })
                .call(() => {
                    if (isClockDayAction) {
                        l.getInstance().playMusic("booster_collect");
                        this.playTagNodeAction();
                        callback && callback();
                        effectNode.active = false;
                        this.recoverEffect(effectNode);
                    } else {
                        effectNode.active = false;
                        this.recoverEffect(effectNode);
                        if (i === effects.length - 1) {
                            callback && callback();
                        } else {
                            this.dealDoneEvent(type);
                        }
                    }
                })
                .start();

            this.node.addChild(effectNode);
        }
    }

    playTagNodeAction() {
        const targetNode = this.getTagNodeByType(this.tarNodes.length - 1);
        cc.tween(targetNode)
            .to(0.05, { scale: 1.1 })
            .to(0.05, { scale: 1 })
            .call(() => {
                targetNode.scale = 1;
            })
            .start();
    }

    dealDoneEvent(type) {
        if (type === n.redPaper) {
            c.trigger(u.CASH_AMPLIFY);
        } else if (type === n.fund) {
            c.trigger(u.FUND_AMPLIFY);
        }
    }

    playEffectMusic(type) {
        let musicName = "";
        if (type === n.redPaper) {
            musicName = "redPaper";
        } else if (type === n.fund) {
            musicName = "fund";
        } else {
            musicName = "prop";
        }
        l.getInstance().playMusic(musicName);
    }

    setCountNodeShow(effectNode, type, reward) {
        const countNode = effectNode.getChildByName("countNode");
        if (countNode) {
            let countString = "";
            if (type >= n.prop) {
                countString = "x" + reward;
                countNode.active = true;
            }
            countNode.getComponent(cc.Label).string = countString;
        }
    }

    recoverEffect(effectNode) {
        this.effectPool.put(effectNode);
    }

    getTagNodeByType(type) {
        for (let i = 0; i < this.tarNodes.length; i++) {
            const nodeData = this.tarNodes[i];
            const nodeType = nodeData.type;
            const tagNode = nodeData.tagNode;
            if (type === nodeType) {
                return tagNode;
            }
        }
        return null;
    }

    isClockDayAction(type, reward) {
        return type >= n.prop && reward && reward > 0;
    }

    setTargetNodes(data) {
        if (data) {
            const nodeArr = data.nodeArr;
            if (nodeArr) {
                this.tarNodes = nodeArr;
                p.log("设置tag节点=======", this.tarNodes);
                this.isEnableWork = true;
            }
        }
    }
}